package py.com.sole.solesys;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.primefaces.event.ScheduleEntryMoveEvent;
import org.primefaces.event.ScheduleEntryResizeEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.DefaultScheduleModel;
import org.primefaces.model.LazyScheduleModel;
import org.primefaces.model.ScheduleEvent;
import org.primefaces.model.ScheduleModel;

import py.com.sole.dao.DaoFactory;
import py.com.sole.model.Clase;
import py.com.sole.model.Estado;
import py.com.sole.util.DateUtil;

@ManagedBean
@ViewScoped
public class CalendarioBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private ScheduleModel eventModel;

	private ScheduleModel lazyEventModel;

	private ScheduleEvent event = new DefaultScheduleEvent();
	
	private Clase clase;
	

	@PostConstruct
	public void init() {
		eventModel = new DefaultScheduleModel();
		List<Clase> clases = DaoFactory.getClase().getClases();
	
		if (null != clases)
		{
			for (Clase clase: clases)
			{
				String cadenaEvento= clase.getMateria().getDescripcion()+ " | " 
						+ clase.getAlumno().getPersona().getNombre().trim() + " " + clase.getAlumno().getPersona().getApellido().trim() + " | " 
						+ clase.getProfesore().getPersona().getNombre().trim() + " " + clase.getProfesore().getPersona().getApellido().trim(); 
				DefaultScheduleEvent evento = 
						new DefaultScheduleEvent(cadenaEvento,
								DateUtil.getDateTime(clase.getFecha(), clase.getHoraInicio()), DateUtil.getDateTime(clase.getFecha(), clase.getHoraFin()));				
				System.out.println("Asignando clase ID: " + clase.getId().toString());
				evento.setData(clase.getId().toString());
				System.out.println("Asignando estilo:" + "evento"+clase.getEstados().getId());
				
				evento.setStyleClass("evento"+clase.getEstados().getId());
				eventModel.addEvent(evento);
			}
		}
			
		/*
		eventModel.addEvent(new DefaultScheduleEvent("Champions League Match",
				previousDay8Pm(), previousDay11Pm()));
		eventModel.addEvent(new DefaultScheduleEvent("Birthday Party",
				today1Pm(), today6Pm()));
		eventModel.addEvent(new DefaultScheduleEvent("Breakfast at Tiffanys",
				nextDay9Am(), nextDay11Am()));
		eventModel.addEvent(new DefaultScheduleEvent(
				"Plant the new garden stuff", theDayAfter3Pm(),
				fourDaysLater3pm()));
		 */
		System.out.println("Inicializando el calendario");
		lazyEventModel = new LazyScheduleModel() {

			@Override
			public void loadEvents(Date start, Date end) {
				Date random = getRandomDate(start);
				addEvent(new DefaultScheduleEvent("Lazy Event 1", random,
						random));

				random = getRandomDate(start);
				addEvent(new DefaultScheduleEvent("Lazy Event 2", random,
						random));
			}
		};
	}

	
	
	public Clase getClase() {
		System.out.println("Calendario: GetClase: validando clase id:" );
		DefaultScheduleEvent evento = (DefaultScheduleEvent) this.event;
		if (null == clase && null != evento.getData())
		{
			Integer eventId = Integer.parseInt((String) evento.getData());
			System.out.println("validando clase id:" +  eventId);			
			clase = DaoFactory.getClase().getClaseById(eventId);
		}
		
		if (null != this.clase && null != evento)
		{
			
			if (!clase.getId().toString().trim().equals(evento.getId().trim()))
			{
				Integer eventId = Integer.parseInt((String) evento.getData());
				System.out.println("validando clase id:" +  eventId);			
				clase = DaoFactory.getClase().getClaseById(eventId);
			}
		}
		return clase;
	}



	public void setClase(Clase clase) {
		this.clase = clase;
	}



	public Date getRandomDate(Date base) {
		Calendar date = Calendar.getInstance();
		date.setTime(base);
		date.add(Calendar.DATE, ((int) (Math.random() * 30)) + 1); // set random
																	// day of
																	// month

		return date.getTime();
	}

	public Date getInitialDate() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(calendar.get(Calendar.YEAR), Calendar.FEBRUARY,
				calendar.get(Calendar.DATE), 0, 0, 0);

		return calendar.getTime();
	}

	public ScheduleModel getEventModel() {
		return eventModel;
	}

	public ScheduleModel getLazyEventModel() {
		return lazyEventModel;
	}

	private Calendar today() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DATE), 0, 0, 0);

		return calendar;
	}
	public String confirmarClase()
	{
		this.cambiarEstadoClase("CONFIRMADO");
		return "";
	}
	public String ausentarClase()
	{
		this.cambiarEstadoClase("AUSENTE");
		return "";
	}
	public String realizarClase()
	{
		this.cambiarEstadoClase("REALIZADO");
		return "clases";
	}

	public void cambiarEstadoClase(String nuevoEstado)
	{
		try{
			if (this.clase != null)
			{
				Estado estado = DaoFactory.getEstado().getEstadoByName(nuevoEstado);
				this.clase.setEstados( estado);
				DaoFactory.getClase().updateClase(clase);
			}	
		}
		catch(Exception ex)
		{
			System.out.println("Error al cambiar el estado de la clase");
		}
		
	}

	
	public ScheduleEvent getEvent() {
		return event;
	}

	public void setEvent(ScheduleEvent event) {
		System.out.println("Calendario: Asignando el id de la clase:");
		this.event = event;
		this.clase = new Clase();
		System.out.println("Calendario: Asignando el id de la clase:"+ event.getId());
		this.clase = DaoFactory.getClase().getClaseById(Integer.parseInt(event.getId()));
	}

	public void addEvent(ActionEvent actionEvent) {
		if (event.getId() == null)
			eventModel.addEvent(event);
		else
			eventModel.updateEvent(event);

		event = new DefaultScheduleEvent();
	}

	public void onEventSelect(SelectEvent selectEvent) {
		event = (ScheduleEvent) selectEvent.getObject();
	}

	public void onDateSelect(SelectEvent selectEvent) {
		event = new DefaultScheduleEvent("", (Date) selectEvent.getObject(),
				(Date) selectEvent.getObject());
	}

	public void onEventMove(ScheduleEntryMoveEvent event) {
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Event moved", "Day delta:" + event.getDayDelta()
						+ ", Minute delta:" + event.getMinuteDelta());

		addMessage(message);
	}

	public void onEventResize(ScheduleEntryResizeEvent event) {
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Event resized", "Day delta:" + event.getDayDelta()
						+ ", Minute delta:" + event.getMinuteDelta());

		addMessage(message);
	}

	private void addMessage(FacesMessage message) {
		FacesContext.getCurrentInstance().addMessage(null, message);
	}
}